# 描述 调用IVS1800 API 接口从摄像机上捕获截图
# 作者 高建设
# 日期 2022-06-17
# 版本 1.0
import json
import threading
import urllib.request
import urllib.parse
import ssl
import os
import time
import datetime
import argparse
import socket
from decimal import Decimal
import shutil
import requests
import smtplib
from email.mime.text import MIMEText
from PIL import Image
import numpy as np
from entity.AlarmInfo import AlarmInfo
import unitys.ActiveMQClient as ActiveMQClient
import jietu_shuimian as jit
import shutil
from collections import Counter
from ultralytics import YOLO
import base64
from unitys.dingding_helper import DingDingHelper
from yolo_predict_update import tupian_yujing

ssl._create_default_https_context = ssl._create_unverified_context
socket.setdefaulttimeout(10)  # 设置默认超时时间为10秒

# IVS1800 IP
ivsIP = 'XX.XX.XX.XX'
# IVS1800端口
ivsPort = '18531'
# 好望云IP
cloudIP = 'api-ivm.myhuaweicloud.com'
# 获取图片间隔分组数
interval_minute = 10
# IVS1800账户用户名
userName = 'apiuser2'
# IVS1800账户密码
password = 'XXXX'
# IVS1800接口获取完整的图片后，拷贝图片到images_ready_path路径，防止送入预警模型的图片不完整。
images_ready_path = 'images/images_ready/'
# 调用IVS1800接口获取图片存储路径
images_pre_path = 'images/images_pre/'
# 调用IVS1800接口获取历史图片存储路径
images_his_path = 'images/images_his/'
# 产生预警标记过的图片
images_alarm_path_alarm = 'images/images_alarm/alarm/'
# 产生预警的原图片
images_alarm_path_ori = 'images/images_alarm/ori/'
# 污水模型文件路径
sewage_detection_path = './models/sewage_detection/'
# 预警图片网络访问地址
alarm_image_url = 'http://10.198.12.21:8088/AlarmImages/'
# 预警视频网络访问地址
alarm_video_url = 'http://10.198.12.21:8088/AlarmVideo/'
site_config_path = './config/site_config_csv/'
# 报警抑制时间（报警时间间隔小时数）
alarm_suppression_time = 5
# 跑预警的开始时间
alarm_start_time = '06:30'
# 跑预警的截止时间
alarm_end_time = '18:30'
# 发送程序健康信息时间间隔分钟数
send_monitor_info_time_interval = 5
# 哪些设备跑预警
black_list = ['09759838908112430101#1185f4f6bb2e4941b9b954198376e30c',
              '2102412503WLN300068066291614420220705165135',
              '2102412503WLN300053266291614420220705165135',
              '2102412503WLN300053566291614420220705165135',
              '2102412503WLN300130266291614420220705165135'
             ]

# 业务系统预警类型与yolov8类别的对应关系
sys_yolo_Mapping = {'GWT001': [0], 'GWT002': [1], 'GWT003': [2]}
sys_warning_typename_Mapping = {'GWT001': '排水', 'GWT002': '污水', 'GWT003': '漂浮物'}

# 请求要携带的凭证
cookie = ''
# 好望云accessToken
access_token = ''
# IVS1800设备列表
device_list = []
# 好望云设备列表
cloud_device_list = []
# IVS1800设备编码与设备名称映射
deviceNameMap = {}
# 好望云设备编码与设备名称映射
coludDeviceNameMap = {}
allDeviceNameMap = {}
# 记录每个设备,每种预警类型最后的报警时间
device_warning_datetime_map = {}
camera_image_is_normal = 1
send_warning_info_is_normal = 1
last_cameras_image_time = '容器刚初始化未赋值'
last_send_warning_info_time = '容器刚初始化未赋值'
last_target_detection_time = '容器刚初始化未赋值'

"""
发送邮件
"""
def sendMail(subject='', text=''):
    try:
        # 确定发送方、邮箱授权码和接收方，邮件主题和内容
        my_from = '294623688@qq.com'  # 发送方
        password = 'ymefaajznfmcbigb'  # 授权码
        to = ['294623688@qq.com']  # 接收方，可以多个接收方，类似于群发
        subject = subject  # 主题
        text = text  # 正文
        #  邮件内容设置
        # MIMEApplication用于发送各种文件，比如压缩，word，excel，pdf等
        '''
        #这一部分是用于发送图片的代码
        imageFile = r"1.jpg"
        imageApart = MIMEImage(open(imageFile, 'rb').read())
        imageApart.add_header('Content-Disposition', 'attachment', filename=imageFile)
        massage = MIMEMultipart()
        massage.attach(imageApart)
        构造邮件
        massage.attach(MIMEText(text,'html'))
        '''
        massage = MIMEText(text)  # 邮件对象
        massage['Subject'] = subject  # 给邮件添加主题
        # massage['From'] = my_from   #谁发送的
        massage['From'] = my_from  # 谁发送的

        massage['To'] = ";".join(to)  # 发给你想发送的对象

        # 发送邮件
        s = smtplib.SMTP_SSL('smtp.qq.com', 465)
        # smtp.qq.com是qq邮箱的服务器地址（SMTP地址），465是他的端口号

        s.login(my_from, password)
        # 登录
        s.sendmail(my_from, to, massage.as_string())
        # 发送方地址，接收方地址，邮件内容
        # massage.as_string()会将邮件原封不动的发送
    except Exception as e:
        print(e)


def base64_to_image(base64_string, output_file_path):
    """
    将 Base64 字符串转换为图片并保存到指定路径

    参数:
        base64_string (str): Base64 编码的字符串
        output_file_path (str): 输出图片文件的路径（例如：'output.png'）
    """
    try:
        # 去除可能的头部信息（如：'data:image/png;base64,'）
        if ',' in base64_string:
            base64_string = base64_string.split(',')[1]

        # 解码 Base64 字符串为二进制数据
        image_data = base64.b64decode(base64_string)

        # 将二进制数据写入图片文件
        with open(output_file_path, 'wb') as image_file:
            image_file.write(image_data)
            image_file.close()

        print(f"图片已成功保存到: {output_file_path}")
    except Exception as e:
        print(f"转换失败: {e}")


"""
发送服务器监控信息
"""


def sendServerMonitoringInfo():
    info = ''
    while 1:
        try:
            if camera_image_is_normal == 1:
                info += '获取图片正常，最后一次获取图片时间是%s\n' % last_cameras_image_time
            if camera_image_is_normal == 0:
                info += '获取图片异常，最后一次获取图片时间是%s\n' % last_cameras_image_time
            if send_warning_info_is_normal == 1:
                info += '发送预警信息正常，最后一次发送预警信息时间是%s\n' % last_send_warning_info_time
            if send_warning_info_is_normal == 0:
                info += '发送预警信息异常，最后一次发送预警信息时间是%s\n' % last_send_warning_info_time
            info += '最后一次成功验证推理功能时间是：%s\n' % last_target_detection_time
            sendMail("泰安视频项目_IVS1800监控信息888_%s" % ivsIP, info)
            info = ''
        except Exception as e:
            sendMail("泰安视频项目_IVS1800监控信息", '发送服务器监控信息出现异常：%s' % e.message)
            print(e)
            print('发送邮件失败')

        time.sleep(60 * send_monitor_info_time_interval)


"""
get、post请求数据
"""


def getRequestData(url='', data={}, headers={}, method=''):
    request = urllib.request.Request(url=url, data=data, headers=headers, method=method)
    response = urllib.request.urlopen(request)
    res = response.read()
    jsonData = json.loads(res)
    return jsonData


"""
下载图片
"""
def downLoadImages(url='', data=None, headers=None, method='', imageName=''):

    res = True
    global camera_image_is_normal, last_cameras_image_time
    request = urllib.request.Request(url=url, data=data, headers=headers, method=method)
    response = urllib.request.urlopen(request)
    img = response.read()
    with open(os.path.join(images_pre_path, imageName), 'wb') as f:
        imageOldFileName = os.path.join(images_pre_path, imageName)
        imageFileName = os.path.join(images_ready_path, imageName)
        if 100 < len(img) < 700000 and response.status == 200:
            f.write(img)
            f.close()
            fileSize = os.path.getsize(imageOldFileName)
            if fileSize == 0:
                os.remove(imageOldFileName)
                res = False
            else:
                shutil.copyfile(imageOldFileName, imageFileName)
                camera_image_is_normal = 1
                last_cameras_image_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        else:
            res = False
            f.close()
            os.remove(imageOldFileName)
            camera_image_is_normal = 0
            if last_cameras_image_time == '':
                last_cameras_image_time = datetime.datetime(1999, 1, 1, 1, 1, 1)
    return res


"""
下载好望云图片
"""
def downLoadCloudImages(url='', data=None, headers=None, method='', imageName=''):
    res = True
    global camera_image_is_normal, last_cameras_image_time
    request = urllib.request.Request(url=url, data={}, headers=headers, method=method)
    response = urllib.request.urlopen(request)
    img = response.read()
    jsonData = json.loads(img)
    pic_url = jsonData['pic_url']
    if pic_url != '' and pic_url is not None:
        data = getRequestData(url='%s?resource_id=2102412503WLN3000549&storage_day=1&channels=true' % pic_url, data=data, headers=headers, method=method)
        pic_data = data['pic_data']
        base64_to_image(pic_data,os.path.join(images_pre_path, imageName))
        imageOldFileName = os.path.join(images_pre_path, imageName)
        imageFileName = os.path.join(images_ready_path, imageName)
        shutil.copyfile(imageOldFileName, imageFileName)
        camera_image_is_normal = 1
        last_cameras_image_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    else:
        res = False
    return res


"""
获取请求凭证
"""
def getRequestCertificate():
    while 1:
        try:
            data = {
                'userName': userName,
                "password": password
            }

            headers = {
                'Content-Type': 'application/json'
            }
            data = bytes(json.dumps(data), 'utf8')
            # global ip, port
            url = 'https://%s:%s/loginInfo/login/v1.0' % (ivsIP, ivsPort)
            request = urllib.request.Request(url=url, data=data, headers=headers, method='POST')
            response = urllib.request.urlopen(request)
            global cookie
            cookie = response.headers.get('Set-Cookie').split(';')[0]
            res = response.read()
            jsonData = json.loads(res)
            return jsonData
        except Exception as e:
            print("获取请求凭证失败%s" % e)
            time.sleep(10)

"""
获取好望云用户登录凭证
"""
def getColudRequestCertificate():
    while 1:
        try:
            data = {
                'ak': '12cfbb2f3d1be244dc7763d6dbe33a59',
                'sk': '1aac198d057a2d5a786c7d97ba617c7332a3778bba8993d58fb6a5dc3f7db58c',
                'force_update': True
            }

            headers = {
                'Content-Type': 'application/json'
            }
            data = bytes(json.dumps(data), 'utf8')
            # global ip, port
            url = 'https://%s/v2/181719091820220705163645/enterprises/access-token' % (cloudIP)
            request = urllib.request.Request(url=url, data=data, headers=headers, method='POST')
            response = urllib.request.urlopen(request)
            global access_token
            res = response.read()
            jsonData = json.loads(res)
            access_token = jsonData['access_token']
            return jsonData
        except Exception as e:
            print("获取请求凭证失败%s" % e)
            time.sleep(10)

"""
获取设备列表
"""
def getDeviceList():
    global device_list, deviceNameMap
    device_list = []
    deviceNameMap = {}
    data = {
    }

    headers = {
        'Content-Type': 'application/json',
        'Cookie': cookie
    }
    data = bytes(json.dumps(data), 'utf8')
    url = 'https://%s:%s/device/deviceList/v1.0?deviceType=2&fromIndex=1&toIndex=1000' % (ivsIP, ivsPort)
    res = getRequestData(url=url, data=data, headers=headers, method='GET')
    if res['resultCode'] == 0:
        device_list = [data['code'] + '#' + data['domainCode'] for data in
                       res['cameraBriefInfos']['cameraBriefInfoList']]
        for item in res['cameraBriefInfos']['cameraBriefInfoList']:
            deviceNameMap[item['code']] = item['name']

    return res


"""
获取好望云设备列表
"""
def getCloudDeviceList():
    global cloud_device_list, coludDeviceNameMap,cloudIP
    cloud_device_list = []
    coludDeviceNameMap = {}
    data = {
    }

    headers = {
        'Content-Type': 'application/json',
        'Access-Token': access_token
    }
    data = bytes(json.dumps(data), 'utf8')
    url = 'https://%s/v1/181719091820220705163645/devices?limit=500' % (cloudIP)
    res = getRequestData(url=url, data=data, headers=headers, method='GET')
    if res['total'] > 0:
        cloud_device_list = [data['device_id'] + '#' + data['org_list'][0]['device_org_id'] for data in res['devices'] if data['device_state'] == 'ONLINE']
        for item in res['devices']:
            if item['device_state'] == 'ONLINE':
                coludDeviceNameMap[item['device_id']] = item['device_name']

    return res

"""
请求保活
"""


def keepAlive():
    while 1:
        try:
            data = {
            }

            headers = {
                'Content-Type': 'application/json',
                'Cookie': cookie
            }
            data = bytes(json.dumps(data), 'utf8')
            url = 'https://%s:%s/common/keepAlive' % (ivsIP, ivsPort)
            res = getRequestData(url=url, data=data, headers=headers, method='GET')
            # 网络状态正常,保活失败时，重新获取登录凭证
            if res['resultCode'] != 0:
                print('重新获取登录凭证')
                getRequestCertificate()
            print('保活方法返回:%s' % res)
        except Exception as e:
            print(e)
            print('keepAlive方法异常')
        time.sleep(60)


"""
清理images_old文件夹过期图片
"""


def clearOldImages():
    while 1:
        for imageFile in os.listdir(images_pre_path):
            imageFilePath = os.path.join(images_pre_path, imageFile)

            try:
                times = imageFile.split('SUV')[-1].split('.')[0]
                times = '%s-%s-%s %s:%s:%s' % (
                    times[0:4], times[4:6], times[6:8], times[8:10], times[10:12], times[12:14])
                times = datetime.datetime.strptime(times, '%Y-%m-%d %H:%M:%S')
                timeNow = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
                timeNow = datetime.datetime.strptime(timeNow, '%Y-%m-%d %H:%M:%S')
                seconds = (timeNow - times).total_seconds()
                if seconds > 10 * 60 and imageFile != 'test%19990707090103.jpg':
                    os.remove(imageFilePath)
            except Exception as e:
                print('清理images_old文件夹失败')
                print(e)
        time.sleep(30)


"""
获取图片
"""


def captures_images():
    # 获取设备截图
    while 1:
        downSuccessCount = 0
        downFailCount = 0
        try:
            startTime = datetime.datetime(2999, 1, 1, int(alarm_start_time.split(':')[0]),
                                          int(alarm_start_time.split(':')[1]))
            endTime = datetime.datetime(2999, 1, 1, int(alarm_end_time.split(':')[0]),
                                        int(alarm_end_time.split(':')[1]))
            nowTime = datetime.datetime(2999, 1, 1, datetime.datetime.now().hour, datetime.datetime.now().minute)
            if not (startTime <= nowTime <= endTime):
                time.sleep(int(Decimal(interval_minute) * 60))
                continue
            for code in device_list:
                data = {
                    'cameraCode': code
                }

                headers = {
                    'Content-Type': 'application/json',
                    'Cookie': cookie
                }
                data = bytes(json.dumps(data), 'utf8')
                url = 'https://%s:%s/snapshot/manualsnapshot' % (ivsIP, ivsPort)
                imageName = code.replace('#', 'XYZ') + 'SUV' + datetime.datetime.now().strftime('%Y%m%d%H%M%S') + '.jpg'
                try:
                    if len(black_list) > 0:
                        if code not in black_list:
                            res = downLoadImages(url=url, data=data, headers=headers, method='POST',
                                                 imageName=imageName)
                            if res:
                                downSuccessCount = downSuccessCount + 1
                            else:
                                downFailCount = downFailCount + 1

                    else:
                        res = downLoadImages(url=url, data=data, headers=headers, method='POST', imageName=imageName)
                        if res:
                            downSuccessCount = downSuccessCount + 1
                        else:
                            downFailCount = downFailCount + 1
                except Exception as e:
                    print('图片%s下载失败' % imageName)
                    print(e)
                    downFailCount = downFailCount + 1
                    continue
                time.sleep(1)
        except Exception as e:
            print(e)
        print('本轮IVS1800图片下载完成，设备%s,成功%s张,失败%s张' % (len(device_list),str(downSuccessCount), str(downFailCount)))
        time.sleep(int(Decimal(interval_minute) * 60))


"""
获取好望云图片
"""
def captures_cloud_images():
    # 获取设备截图
    while 1:
        downSuccessCountCloud = 0
        downFailCountCloud = 0
        try:
            startTime = datetime.datetime(2999, 1, 1, int(alarm_start_time.split(':')[0]),
                                          int(alarm_start_time.split(':')[1]))
            endTime = datetime.datetime(2999, 1, 1, int(alarm_end_time.split(':')[0]),
                                        int(alarm_end_time.split(':')[1]))
            nowTime = datetime.datetime(2999, 1, 1, datetime.datetime.now().hour, datetime.datetime.now().minute)
            if not (startTime <= nowTime <= endTime):
                time.sleep(int(Decimal(interval_minute) * 60))
                continue
            for code in cloud_device_list:
                data = {
                }

                headers = {
                    'Content-Type': 'application/json',
                    'Access-Token': access_token
                }
                data = bytes(json.dumps(data), 'utf8')
                device_id = code.split('#')[0]
                url = 'https://%s/v1/181719091820220705163645/devices/snap?device_id=%s&channel_id=0&storage=true' % (cloudIP,device_id)
                imageName = code.replace('#', 'XYZ') + 'SUV' + datetime.datetime.now().strftime('%Y%m%d%H%M%S') + '.jpg'
                try:
                    if len(black_list) > 0:
                        if code not in black_list:
                            res = downLoadCloudImages(url=url, data=data, headers=headers, method='GET',
                                                      imageName=imageName)
                            if res:
                                downSuccessCountCloud = downSuccessCountCloud + 1
                            else:
                                downFailCountCloud = downFailCountCloud + 1

                    else:
                        res = downLoadCloudImages(url=url, data=data, headers=headers, method='GET',
                                                  imageName=imageName)
                        if res:
                            downSuccessCountCloud = downSuccessCountCloud + 1
                        else:
                            downFailCountCloud = downFailCountCloud + 1
                except Exception as e:
                    print('图片%s下载失败' % imageName)
                    print(e)
                    downFailCountCloud = downFailCountCloud + 1
                    continue
                time.sleep(1)
        except Exception as e:
            print(e)
        print('本轮好望云图片下载完成，设备%s,成功%s张,失败%s张' % (len(cloud_device_list), str(downSuccessCountCloud), str(downFailCountCloud)))
        time.sleep(int(Decimal(interval_minute) * 60))


"""
跑目标检测算法
"""


def get_sys_yolo_mapping_num(counter):
    map_list = {'GWT001': 0, 'GWT002': 0, 'GWT003': 0}
    for key, value in counter.items():
        for map_key, map_value in sys_yolo_Mapping.items():
            if key in map_value:
                map_list[map_key] = map_list[map_key] + value
    return map_list


"""
跑目标检测算法
"""


def objectDetection():
    # 读取images_ready路径下图片
    model = YOLO("models/best.pt")  # load an official model
    while True:
        alarmInfoList = []
        # Predict with the model
        for imageFile in os.listdir(images_ready_path):
            print(imageFile + '#################')
            date_string = imageFile.split('SUV')[1].split('.')[0]
            year = int(date_string[:4])
            month = int(date_string[4:6])
            day = int(date_string[6:8])
            hour = int(date_string[8:10])
            minute = int(date_string[10:12])
            second = int(date_string[12:14])
            imageFilePath = os.path.join(images_ready_path, imageFile)
            csv_path = os.path.join(site_config_path, allDeviceNameMap[imageFile.split('XYZ')[0]] + '.csv')
            if not os.path.exists(csv_path):
                print(f'{csv_path}不存在')
                csv_path = None
            # 运行目标监测算法
            path = f'{images_alarm_path_alarm}/{datetime.datetime(year, month, day, hour, minute, second).strftime(
                '%Y-%m-%d')}/{allDeviceNameMap[imageFile.split('XYZ')[0]]}'
            if not os.path.exists(path):
                os.makedirs(path)

            cls_list = tupian_yujing(imageFilePath, csv_path, path, model,
                                     device_name=imageFile.split('SUV')[0].replace('XYZ', '#'))
            if len(cls_list) > 0:
                # 检测到目标对象保存预警图片
                # print(results[0].boxes)
                plist = get_sys_yolo_mapping_num(Counter(cls_list))
                is_exist_alarm = 0
                for key, value in plist.items():
                    if value > 0:
                        is_exist_alarm = 1
                if is_exist_alarm == 1:
                    # 保存一份抓拍的原图
                    path = f'{images_alarm_path_ori}/{datetime.datetime(year, month, day, hour, minute, second).strftime(
                        '%Y-%m-%d')}/{allDeviceNameMap[imageFile.split('XYZ')[0]]}'
                    if not os.path.exists(path):
                        os.makedirs(path)
                    shutil.copy(imageFilePath, os.path.join(path, imageFile))
                    for key, value in plist.items():
                        if value == 0:
                            continue
                        alarmInfo = AlarmInfo()
                        alarmInfo.AlarmTime = datetime.datetime(year, month, day, hour, minute, second).strftime(
                            '%Y-%m-%d %H:%M:%S')
                        alarmInfo.DeviceId = imageFile.split('SUV')[0].replace('XYZ', '#')
                        alarmInfo.DeviceName = allDeviceNameMap[imageFile.split('XYZ')[0]]
                        alarmInfo.AlarmImageName = imageFile
                        path = f'{alarm_image_url}{datetime.datetime(year, month, day, hour, minute, second).strftime(
                            '%Y-%m-%d')}/{allDeviceNameMap[imageFile.split('XYZ')[0]]}/'
                        alarmInfo.AlarmImageUrl = os.path.join(path, imageFile)
                        path = f'{alarm_video_url}{datetime.datetime(year, month, day, hour, minute, second).strftime(
                            '%Y-%m-%d')}/{allDeviceNameMap[imageFile.split('XYZ')[0]]}/'
                        alarmInfo.AlarmVideoUrl = os.path.join(path, imageFile.replace('jpg', 'mp4'))
                        alarmInfo.AlarmClassId = key
                        alarmInfo.AlarmTargetNum = value
                        alarmInfoList.append(alarmInfo)
                        # 往钉钉群推送告警消息
                        print('#######################################################################')
                        if alarmInfo.AlarmClassId == 'GWT001':
                            now_day = datetime.datetime.now().strftime("%Y-%m-%d")
                            if alarmInfo.DeviceId not in device_warning_datetime_map:
                                # 设备不在字典
                                device_warning_datetime_map[alarmInfo.DeviceId] = {}
                                device_warning_datetime_map[alarmInfo.DeviceId][alarmInfo.AlarmClassId] = now_day
                                send_video_alarm(alarmInfo)
                            else:
                                # 设备在字典，判断该预警类型是否在字典
                                if alarmInfo.AlarmClassId not in device_warning_datetime_map[alarmInfo.DeviceId]:
                                    device_warning_datetime_map[alarmInfo.DeviceId][alarmInfo.AlarmClassId] = now_day
                                    send_video_alarm(alarmInfo)
                                else:
                                    # 获取最后的预警时间
                                    last_time = device_warning_datetime_map[alarmInfo.DeviceId][alarmInfo.AlarmClassId]
                                    if now_day != last_time:
                                        device_warning_datetime_map[alarmInfo.DeviceId][alarmInfo.AlarmClassId] = now_day
                                        send_video_alarm(alarmInfo)
                            # 保存设备预警时间到文件
                            with open('./config/waring_last_time.json', 'w') as file:
                                json.dump(device_warning_datetime_map, file)

                        # rtmp_to_flv文件夹写入获取视频流的文件名字
                        # 创建文件
                        with open('./rtsp_to_flv/{}.txt'.format(imageFile.split('.')[0]), 'w') as file:
                            file.write(cookie + '\n')
                            file.write(alarmInfo.DeviceName + '\n')
                        print(f'键: {key}, 值: {value}')
            # 预测完成把图片移动到历史图片文件夹
            path = f'{images_his_path}{datetime.datetime(year, month, day, hour, minute, second).strftime(
                '%Y-%m-%d')}/{allDeviceNameMap[imageFile.split('XYZ')[0]]}/'
            if not os.path.exists(path):
                os.makedirs(path)
            shutil.copy(imageFilePath, os.path.join(path, imageFile))
            os.remove(imageFilePath)

        if len(alarmInfoList) > 0:
            pass
            #ActiveMQClient.send_mq_multiple(alarmInfoList)
        time.sleep(5)


def send_video_alarm(alarmInfo):
    message = "### 视频告警测试数据" + '\n'
    message += '---' + '\n'
    message += f"+ **告警时间:** {alarmInfo.AlarmTime}" + '\n'
    message += f"+ **设备编码:** {alarmInfo.DeviceId}" + '\n'
    message += f"+ **设备名称:** {alarmInfo.DeviceName}" + '\n'
    message += f"+ **告警类型:** {sys_warning_typename_Mapping[alarmInfo.AlarmClassId]}" + '\n'
    message += f"+ **告警图片:** [告警图片]({alarmInfo.AlarmImageUrl.replace('10.198.12.21', '121.89.192.235')})" + '\n'
    message += f"+ **目标数量:** {alarmInfo.AlarmTargetNum}" + '\n'
    print(message)
    DingDingHelper().send_message("视频告警信息", message, "")


"""
定时发送消息到消息队列,防止消费者掉线
"""


def sendAliveMessage():
    while 1:
        #ActiveMQClient.sendMessage("alive")
        time.sleep(60)
def load_config_info():
    global device_warning_datetime_map
    # 读取设备预警最后报警时间
    if os.path.exists('./config/waring_last_time.json'):
        with open('./config/waring_last_time.json', 'r', encoding='utf-8') as f:
            try:
                device_warning_datetime_map = json.load(f)
            except Exception as e:
                print(e)
    else:
        device_warning_datetime_map = {}

def parse_args():
    """
       :return:进行参数的解析
       """
    description = "you should add those parameter"
    parser = argparse.ArgumentParser(description=description)
    parser.add_argument('-ivsIP', help='IVS1800 API ip')
    parser.add_argument('-ivsPort', help='IVS1800 API port')
    parser.add_argument('-interval_minute', help='IVS1800 API camera images_ready interval_minute')
    args = parser.parse_args()
    return args


if __name__ == '__main__':
    # args = parse_args()
    # ivsIP = args.ivsIP
    # ivsPort = args.ivsPort
    # interval_minute = args.interval_minute
    try:
        if ivsIP is None or ivsPort is None:
            raise Exception('请传入IVS1800 API ip,port!')
        if interval_minute is None:
            raise Exception('请传入IVS1800 API interval_minute!')

        # 读取配置信息
        load_config_info()
        # 获取请求凭证
        res = getRequestCertificate()
        if res['resultCode'] != 0:
            print('获取凭证失败')
        # 获取好望云登录凭证
        res = getColudRequestCertificate()
        if 'access_token' not in res:
            print('获取凭证失败')
        # 请求保活
        t = threading.Thread(target=keepAlive, args=())
        t.start()

        if cookie != '':
            # 首先拿到IVS1800设备列表
            getDeviceList()
            # 首先拿到好望云设备列表
            getCloudDeviceList()
            allDeviceNameMap = {**deviceNameMap, **coludDeviceNameMap}
            # 开启线程发送服务器监控信息
            m = threading.Thread(target=sendServerMonitoringInfo, args=())
            m.start()

            # 清理images_old过期文件
            m = threading.Thread(target=clearOldImages, args=())
            m.start()

            # 抓取IVS1800摄像机图片
            m = threading.Thread(target=captures_images, args=())
            m.start()

            # 抓取好望云摄像机图片
            m = threading.Thread(target=captures_cloud_images, args=())
            m.start()

            # 消息队列保活
            m = threading.Thread(target=sendAliveMessage, args=())
            m.start()

            # 对抓取的图片跑yolov8目标检测算法
            objectDetection()

    except Exception as e:
        print(str(e))
        print('调用格式 python3 CameraImages.py -ivsIP 111.36.100.199 -ivsPort 18531 -interval_minute 5')
